package com.example.webrestfulcrud.controller;

import com.example.webrestfulcrud.exception.MyUserNotExistExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import java.util.Map;

//@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class MyCustomizedBasicErrorController extends AbstractErrorController {


    /**
     * 必须有构造器存在，用于给父类的ErrorViewResolver赋值（ErrorViewResolver从IOC容器中自动获取）
     * @param errorAttributes
     * @param errorViewResolvers
     */
    public MyCustomizedBasicErrorController(ErrorAttributes errorAttributes, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorViewResolvers);
    }

    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);

        response.setStatus(status.value());

        Map<String, Object> errorMap =(Map<String, Object>) request.getAttribute(MyUserNotExistExceptionHandler.MY_ERROR_MAP);

        /**
         * 构造器中必须配置父类的ErrorViewResolver，否则无法解析到错误视图4xx.html,5xx.html
         */
        ModelAndView modelAndView = resolveErrorView(request, response, status, errorMap);

        return (modelAndView != null) ? modelAndView : new ModelAndView("error", errorMap);
    }

    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> errorMap =(Map<String, Object>) request.getAttribute(MyUserNotExistExceptionHandler.MY_ERROR_MAP);
        return new ResponseEntity<>(errorMap, status);
    }

    @Override
    public String getErrorPath() {
        return null;
    }

}
